package com.demo.多线程;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Program: java
 * @ClassName Ticket
 * @Author: liutao
 * @Description: 并发买票：Lock
 * @Create: 2023-10-26 22:48
 * @Version 1.0
 **/


public class LockTicket implements Runnable{
    private final Lock lock = new ReentrantLock();
    boolean flag = true;
    private int ticketNum = 10;

    public static void main(String[] args) {
        LockTicket ticket = new LockTicket();
        new Thread(ticket,"小明").start();
        new Thread(ticket,"小红").start();
        new Thread(ticket,"李白").start();
    }

    @Override
    public void run() {
        while (flag) {
            // 加锁
            lock.lock();
            try {
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                // 解锁
                lock.unlock();
            }
        }
    }

    private void buy() throws InterruptedException {
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + "抢到了第"+ticketNum--+"票");
        Thread.sleep(100);
    }
}
